package com.rickpan.repository;

import com.rickpan.entity.UserApiKey;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

/**
 * 用户API Key数据访问接口
 */
@Repository
public interface UserApiKeyRepository extends JpaRepository<UserApiKey, Long> {

    /**
     * 根据用户ID查找API Key配置
     * @param userId 用户ID
     * @return API Key配置
     */
    Optional<UserApiKey> findByUserId(Long userId);

    /**
     * 根据用户ID查找激活的API Key配置
     * @param userId 用户ID
     * @return 激活的API Key配置
     */
    @Query("SELECT u FROM UserApiKey u WHERE u.userId = :userId AND u.isActive = true")
    Optional<UserApiKey> findActiveByUserId(@Param("userId") Long userId);

    /**
     * 检查用户是否已配置API Key
     * @param userId 用户ID
     * @return 是否存在配置
     */
    boolean existsByUserId(Long userId);

    /**
     * 检查用户是否有激活的API Key
     * @param userId 用户ID
     * @return 是否有激活的配置
     */
    @Query("SELECT COUNT(u) > 0 FROM UserApiKey u WHERE u.userId = :userId AND u.isActive = true")
    boolean existsActiveByUserId(@Param("userId") Long userId);
}
